package com.cndw.kungfu.ext;

import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsConfig;

public class PropertiesLib {

	public static final String nameXml = "playName";
	
	
	private static ConcurrentHashMap<String,Properties> properMaps = new ConcurrentHashMap<String, Properties>();
	
	private static ConcurrentHashMap<String, Map<String, String[]>> properArr = new ConcurrentHashMap<String, Map<String,String[]>>();
	
	public static Properties load(String fileName){
		try {
			Properties temp = new Properties();
			InputStreamReader input = new InputStreamReader(PropertiesLib.class.getResourceAsStream("/" + ConstantsConfig.getLocaleResource() + fileName+".properties"),"UTF-8");
			temp.load(input);
			input.close();
			return temp;			
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}		
	}
	
	public static void updateCache(){
		properMaps.clear();
	}
	
	public static String getValue(String rootName,String key){
		if (!properMaps.containsKey(rootName)) {
			synchronized (PropertiesLib.class) {
				if (!properMaps.containsKey(rootName)) {
					Properties temp = load(rootName);
					properMaps.put(rootName, temp);
				}
			}			
			
		}
		Properties properties = properMaps.get(rootName);		
		if(properties!=null){
			String property=properties.getProperty(key);
			return property;
		}
		return "";
	}
	
	public static String[] getCacheArr(String rootName,String key){
		if (!properArr.containsKey(rootName)) {
			properArr.putIfAbsent(rootName, new HashMap<String, String[]>());
		}
		if (properArr.get(rootName).containsKey(key)==false) {
			synchronized (properArr.get(rootName)) {
				if (properArr.get(rootName).containsKey(key)==false){
					String values = getValue(rootName, key);
					String[] arrValues = values.split(Constants.COMMSPLIT);
					properArr.get(rootName).put(key, arrValues);
				}
			}
		}		
		return properArr.get(rootName).get(key);
	}
	
	
	public static String getArrayValue(String rootName,String key){
		
		String[] arrValues = getCacheArr(rootName,key);
		Random random = new Random();
		
		int ranindex = random.nextInt(arrValues.length);
		if (arrValues[ranindex] != null ) {
			return arrValues[ranindex];
		}else{
			return "";
		}
		
	}
	
	
	
	
	
	
	
	
	
	

	
}
